package com.ggh.smartreply;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class AddDataBaseActivity extends Activity {

    private EditText checkText = null;
    private EditText replyText = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.adddatabaseactivity);

        checkText = (EditText)findViewById(R.id.checkText);
        replyText = (EditText)findViewById(R.id.replyText);

        Button addRule = (Button)findViewById(R.id.addRule);
        Button cancel = (Button)findViewById(R.id.cancel);

        addRule.setOnClickListener(new AddRuleButtonListener());
        cancel.setOnClickListener(new CancelButtonListener());
    }

    class AddRuleButtonListener implements View.OnClickListener{

        @Override
        public void onClick(View view) {

            RuleDataBaseHelper ruleDataBaseHelper = new RuleDataBaseHelper(AddDataBaseActivity.this,"text_RULE");
            SQLiteDatabase db = ruleDataBaseHelper.getReadableDatabase();

            Cursor cursor = db.query("RULE",null,null,null,null,null,null,null);

            if(checkDatabase(cursor)){
                cursor.close();
                db.close();
                Toast.makeText(AddDataBaseActivity.this, "该规则已存在，请添加其他规则", Toast.LENGTH_SHORT).show();
            }
            else{
                ContentValues values = new ContentValues();
                values.put("_check",checkText.getText().toString());
                values.put("_reply",replyText.getText().toString());
                db = ruleDataBaseHelper.getWritableDatabase();
                db.insert("RULE",null,values);
                cursor.close();
                db.close();
                finish();
            }

        }

        public boolean checkDatabase(Cursor cursor){

            for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){

                if(checkText.getText().toString().equals(cursor.getString(cursor.getColumnIndex("_check"))) ){
                    return true;
                }
            }
            return false;
        }
    }

    class CancelButtonListener implements View.OnClickListener{


        @Override
        public void onClick(View view) {
            finish();
        }
    }
}
